<template>
  <div class="make-booking-page">
    <h2>预订会议室</h2>

    <!-- Step 1: Submit Reservation Requirements -->
    <section class="booking-form-section">
      <h3>填写预约要求</h3>
      <form @submit.prevent="handleSearchRooms" class="booking-form">
        <div class="form-group">
          <label for="booking-date">选择日期:</label>
          <input type="date" id="booking-date" v-model="searchCriteria.date" required :min="minDate" :max="maxDate" />
        </div>

        <div class="form-group time-selection">
          <label for="start-time">开始时间:</label>
          <select id="start-time" v-model="searchCriteria.startTime" required>
            <option v-for="hour in availableHours" :key="hour" :value="`${hour}:00:00`">
              {{ hour }}:00
            </option>
          </select>

          <label for="end-time">结束时间:</label>
          <select id="end-time" v-model="searchCriteria.endTime" required>
            <option v-for="hour in availableHours" :key="hour" :value="`${hour}:00:00`">
              {{ hour }}:00
            </option>
          </select>
        </div>

        <div class="form-group">
          <label for="capacity">参会人数:</label>
          <input type="number" id="capacity" v-model.number="searchCriteria.capacity" min="1" required />
        </div>

        <div class="form-group equipment-checkboxes">
          <label>所需设备:</label>
          <div>
            <input type="checkbox" id="projector" value="projector" v-model="searchCriteria.equipment" />
            <label for="projector">投影仪</label>
          </div>
          <div>
            <input type="checkbox" id="sound" value="sound" v-model="searchCriteria.equipment" />
            <label for="sound">音响系统</label>
          </div>
          <div>
            <input type="checkbox" id="internet" value="internet" v-model="searchCriteria.equipment" />
            <label for="internet">网络</label>
          </div>
        </div>

        <button type="submit" class="search-button">搜索会议室</button>
      </form>
    </section>

    <!-- Step 2: System Filter and Recommend -->
    <section v-if="searchResults.length > 0" class="search-results-section">
      <h3>符合条件的会议室</h3>
      <div class="filter-controls">
        <label for="resultRoomTypeFilter">筛选会议室类型:</label>
        <select id="resultRoomTypeFilter" v-model="selectedResultRoomType">
          <option value="all">所有类型</option>
          <option value="1">教室</option>
          <option value="2">圆桌</option>
          <option value="3">董事会</option>
          <option value="4">多媒体</option>
        </select>
      </div>
      <div v-if="filteredSearchResults.length === 0" class="no-results">
        没有找到符合当前筛选条件的会议室。
      </div>
      <ul v-else class="room-results-list">
        <li v-for="room in filteredSearchResults" :key="room.roomId" class="room-result-item">
          <h4>{{ room.roomname }} ({{ getRoomType(room.roomType) }})</h4>
          <p><strong>容纳人数:</strong> {{ room.capacity }}人</p>
          <p><strong>设备:</strong>
            <span v-if="room.projector === 1">投影仪</span>
            <span v-if="room.sound === 1">音响</span>
            <span v-if="room.internet === 1">网络</span>
            <span v-if="room.projector === 0 || room.sound === 0 || room.internet === 0"> (部分设备异常)</span>
          </p>
          <p><strong>每小时租赁价格:</strong> ¥{{ room.price }}</p>
          <button @click="selectRoom(room)" class="select-button">选择</button>
        </li>
      </ul>
    </section>

    <section v-else-if="searched && searchResults.length === 0" class="no-results-section">
      <h3>没有找到符合条件的会议室。</h3>
      <p>请尝试调整您的搜索条件。</p>
    </section>

  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { searchRooms } from '@/apis/room';
import { createReservationOrder } from '@/apis/orders';
import { useUserStore } from '@/stores/user';
import { useBookingTempStore } from '@/stores/bookingTemp';

const router = useRouter();
const userStore = useUserStore();
const bookingTempStore = useBookingTempStore();

const searchCriteria = ref({
  date: '',
  startTime: '09:00:00',
  endTime: '10:00:00',
  capacity: 1,
  equipment: [],
});

const searchResults = ref([]);
const searched = ref(false);
const selectedRoom = ref(null);
const selectedResultRoomType = ref('all'); // 'all' for all types, or a number for specific type

const filteredSearchResults = computed(() => {
  if (selectedResultRoomType.value === 'all') {
    return searchResults.value;
  }
  return searchResults.value.filter(room => room.roomType === parseInt(selectedResultRoomType.value));
});
const currentBooking = ref(null); // Stores the order after creation

const userId = computed(() => userStore.user?.id);

// Generate available hours for dropdowns
const availableHours = computed(() => {
  const hours = [];
  for (let i = 9; i <= 18; i++) { // From 9 AM to 6 PM
    hours.push(String(i).padStart(2, '0'));
  }
  return hours;
});

// Date limits for booking
const minDate = computed(() => {
  const today = new Date();
  return today.toISOString().split('T')[0];
});

const maxDate = computed(() => {
  const futureDate = new Date();
  futureDate.setDate(futureDate.getDate() + 60); // 60 days in advance
  return futureDate.toISOString().split('T')[0];
});

// Helper function to map room_type to readable string
const getRoomType = (type) => {
  switch (type) {
    case 1: return '教室';
    case 2: return '圆桌';
    case 3: return '董事会';
    case 4: return '多媒体';
    default: return '未知类型';
  }
};

// Calculate total fee
const calculatedTotalFee = computed(() => {
  if (!selectedRoom.value || !searchCriteria.value.startTime || !searchCriteria.value.endTime) {
    return 0;
  }
  const startHour = parseInt(searchCriteria.value.startTime.substring(0, 2));
  const endHour = parseInt(searchCriteria.value.endTime.substring(0, 2));
  const duration = endHour - startHour;
  return selectedRoom.value.price * duration;
});

// Handle search rooms
const handleSearchRooms = async () => {
  searched.value = true;
  selectedRoom.value = null; // Reset selected room
  currentBooking.value = null; // Reset current booking

  try {
    const criteria = {
      capacity: searchCriteria.value.capacity,
      projector: searchCriteria.value.equipment.includes('projector') ? 1 : 0,
      sound: searchCriteria.value.equipment.includes('sound') ? 1 : 0,
      internet: searchCriteria.value.equipment.includes('internet') ? 1 : 0,
      startTime: `${searchCriteria.value.date}T${searchCriteria.value.startTime}`,
      endTime: `${searchCriteria.value.date}T${searchCriteria.value.endTime}`,
    };

    const response = await searchRooms(criteria);
    if (response.code === 200 && response.data) {
      searchResults.value = response.data;
    } else {
      console.error('Failed to search rooms:', response.msg);
      searchResults.value = [];
    }
  } catch (error) {
    console.error('Failed to search rooms:', error);
    searchResults.value = [];
  }
};

// Handle room selection
const selectRoom = async (room) => {
  selectedRoom.value = room;
  // Automatically create booking after selection
  try {
    const orderData = {
      userId: String(userId.value), // Ensure userId is string and get its value
      roomId: String(room.roomId), // Ensure roomId is string as per API example
      startTime: `${searchCriteria.value.date}T${searchCriteria.value.startTime}`,
      endTime: `${searchCriteria.value.date}T${searchCriteria.value.endTime}`,
    };
    const response = await createReservationOrder(orderData);

    if (response.code === 200 && response.data) {
      const bookingDetails = response.data;
      currentBooking.value = bookingDetails;
      bookingTempStore.setTempBookingDetails(bookingDetails); // Store full details
      // Removed alert as details will be shown on the next page
      router.push({ name: 'BookingDetails', params: { id: bookingDetails.orderId } });
    } else {
      console.error('Failed to create booking:', response.msg);
      alert(`生成订单失败: ${response.msg}`);
      selectedRoom.value = null; // Reset selection on failure
    }
  } catch (error) {
    console.error('Failed to create booking:', error);
    alert('生成订单失败，请重试。');
    selectedRoom.value = null; // Reset selection on failure
  }
};

onMounted(() => {
  // Set initial date to today
  searchCriteria.value.date = minDate.value;
});
</script>

<style scoped>
.make-booking-page {
  padding: 2rem;
  max-width: 900px;
  margin: 0 auto;
  font-family: 'Arial', sans-serif;
}

h2 {
  color: #333;
  text-align: center;
  margin-bottom: 2rem;
}

section {
  background-color: #f9f9f9;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 2rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

h3 {
  color: #0056b3;
  margin-top: 0;
  margin-bottom: 1rem;
  border-bottom: 2px solid #eee;
  padding-bottom: 0.5rem;
}

.booking-form {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.form-group {
  display: flex;
  flex-direction: column;
}

.form-group label {
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: #555;
}

.form-group input[type="date"],
.form-group input[type="number"],
.form-group select {
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 1rem;
}

.time-selection {
  display: flex;
  flex-direction: row;
  align-items: center;
  gap: 1rem;
}

.time-selection label {
  margin-bottom: 0;
}

.equipment-checkboxes div {
  display: flex;
  align-items: center;
  margin-bottom: 0.5rem;
}

.equipment-checkboxes input[type="checkbox"] {
  margin-right: 0.5rem;
}

.search-button {
  grid-column: 1 / -1; /* Span across both columns */
  padding: 1rem 2rem;
  background-color: #1976d2;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1.1rem;
  transition: background-color 0.3s ease;
}

.search-button:hover {
  background-color: #135ba1;
}

.search-results-section .room-results-list {
  list-style: none;
  padding: 0;
  margin: 0;
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* Adjusted min-width for more columns */
  gap: 1.5rem;
}

.room-result-item {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1.2rem;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.room-result-item h4 {
  color: #1976d2;
  margin-top: 0;
  margin-bottom: 0.8rem;
  font-size: 1.1rem;
}

.room-result-item p {
  margin: 0.4rem 0;
  color: #555;
  font-size: 0.9rem;
}

.room-result-item p strong {
  color: #333;
}

.select-button {
  padding: 0.8rem 1.5rem;
  background-color: #28a745;
  color: #fff;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1rem;
  margin-top: 1rem;
  align-self: flex-end; /* Align button to the bottom right */
  transition: background-color 0.3s ease;
}

.select-button:hover {
  background-color: #218838;
}

.no-results-section {
  text-align: center;
  color: #666;
  padding: 1rem;
  background-color: #e9e9e9;
  border-radius: 4px;
}

.booking-confirmation-section {
  text-align: center;
}

.confirmation-details {
  background-color: #e7f3ff;
  border: 1px solid #b3d9ff;
  border-radius: 8px;
  padding: 1.5rem;
  margin-bottom: 1.5rem;
}

.confirmation-details p {
  margin-bottom: 0.5rem;
  font-size: 1.1rem;
}

.confirmation-details p strong {
  color: #0056b3;
}

.countdown {
  font-weight: bold;
  color: #dc3545;
  font-size: 1.2rem;
}

.payment-actions button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  font-size: 1.1rem;
  margin: 0 0.5rem;
  transition: background-color 0.3s ease;
}

.payment-actions .success {
  background-color: #28a745;
  color: #fff;
}

.payment-actions .success:hover {
  background-color: #218838;
}

.payment-actions .fail {
  background-color: #dc3545;
  color: #fff;
}

.payment-actions .fail:hover {
  background-color: #c82333;
}

.filter-controls {
  margin-bottom: 1.5rem;
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-controls label {
  font-weight: bold;
  color: #555;
}

.filter-controls select {
  padding: 8px 12px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 1rem;
  cursor: pointer;
  background-color: #fff;
}

.filter-controls select:focus {
  outline: none;
  border-color: #007bff;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.25);
}

.no-results {
  color: #666;
  text-align: center;
  padding: 1rem;
  background-color: #e9e9e9;
  border-radius: 4px;
  margin-top: 1rem;
}
</style>
